import { _decorator, Button, Label, tween, Tween, UIOpacity, v3 } from 'cc';
import { DataProxy } from '../../../frame/A-LIB/lib.b.data';
import { BasePopUp } from '../../../frame/component/ui.pop-up';
import { ClientAPI } from '../../api/client.api';
import GameDC from '../../manager/data.game.center';
import GameAssets from '../../manager/game.assets';
import type { Popup } from '../page/popup';
const { ccclass, property } = _decorator;

@ccclass('Setting')
export class Setting extends BasePopUp<typeof Popup, null> {
	protected default_return: null;

	protected initAfterOnLoad(){
		this.renderLocalUI();
	}

	protected _click_event_: { [name: string]: (this: Setting, button: Button) => void; } = {
		close(btn){
			btn.interactable = false;
			BasePopUp.jelly_leave(this.node).then(()=>{
				this.close(null);
				btn.interactable = true;
			});
		},
		bgm(){
			let pick = !GameDC.User.bgm;
			GameDC.User.bgm = pick;
		},
		['user-info'](){
			ClientAPI.SetClipboard(GameDC.Status.deviceID);
		},
		deviceid(){
			ClientAPI.SetClipboard(GameDC.Status.deviceID);
		}
	}

	public onShow(){
		this.setPickUI(GameDC.User.bgm);
		BasePopUp.jelly_enter(this.node);
	}

	protected listening(){
		let list = [];
		list.push(
			DataProxy.follow(GameDC.User, 'bgm', (_, pick)=>{
				this.setPickUI(pick);
			})
		)
		return list;
	}

	private renderLocalUI(){
		(<const>[
			['lbl-head', 14],
			['lbl-bgm', 15],
		]).forEach(([name, idx])=>this.node.getChildByName(name).getComponent(Label).string = GameAssets.getLangText(idx));

		this.node.getChildByName('lbl-nickname').getComponent(Label).string = 'MatchMagic';
		this.node.getChildByName('lbl-deviceid').getComponent(Label).string = GameDC.Status.deviceID;
	}

	private pick_handle_position = v3();
	private setPickUI(pick: boolean){
		let type = pick ? 'on' : 'off';

		let duration = 0.1;

		let node_pick = this.__btn_map__.get('bgm').node.getChildByName('pick');
		['background', 'handle'].forEach(name=>{
			node_pick.getChildByName(name)
			.getComponentsInChildren(UIOpacity)
			.forEach(opt=>{
				Tween.stopAllByTarget(opt);
				opt.node.setPosition(0, 0, opt.node.position.z);
				tween(opt)
				.to(duration, {opacity: opt.node.name==type ? 255 : 0})
				.start();
			});
		});

		let node_handle = node_pick.getChildByName('handle');
		this.pick_handle_position.set(0, 0, node_handle.position.z);
		this.pick_handle_position.x = pick ? 100 : -100;

		Tween.stopAllByTarget(node_handle);
		tween(node_handle)
		.to(duration, {position: this.pick_handle_position})
		.start();
	}
}

